package com.tpc.pictool.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

@Component
public class PDFUtils {
    public static void pdfToImageFile(String fileName) throws Exception {
        PDDocument doc = null;
        ByteArrayOutputStream os = null;
        InputStream stream = null;
        OutputStream out = null;

        try {
            stream = new FileInputStream(fileName);
            doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            File file = new File(fileName);
            os = new ByteArrayOutputStream();
            byte[] dataList = os.toByteArray();
            for(int i = 0; i < pageCount; ++i) {
                if (i == 0) {
                    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200.0F);

                    ImageIO.write(bim, "png", os);

                    fileName = fileName.replaceAll(".pdf", ".png");

                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }

                    out = new FileOutputStream(file);
                    out.write(dataList);
                }
            }
        } catch (Exception var15) {
            var15.printStackTrace();
            throw var15;
        } finally {
            if (doc != null) {
                doc.close();
            }

            if (os != null) {
                os.close();
            }

            if (stream != null) {
                stream.close();
            }

            if (out != null) {
                out.close();
            }

        }

    }
}
